package userShareModuleApi

import (
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/utils"
	"errors"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis"
)

func (UserShareModuleApi) ShareDownload(c *gin.Context) {
	code := c.Param("code")
	if code == "" {
		c.JSON(400, gin.H{"error": "链接无效"})
	}
	downloadId := enums.ShareDownloadId.GetDownloadId(code)
	fileTrees, err := utils.GetDownloadIdOfFileInfo(downloadId)
	if err != nil {
		if errors.Is(err, redis.Nil) {
			c.JSON(404, gin.H{"error": "文件不存在"})
			return
		}
		c.JSON(500, gin.H{"error": "服务器错误"})
		return
	}
	var buffer []byte
	var fileName string
	if fileTrees[0].IsFolder != enums.Folder {
		buffer, err = utils.GenerateFileFromStruct(fileTrees)
		fileName = fileTrees[0].FileName
	} else {
		buffer, err = utils.GenerateZipFromStruct(fileTrees)
		fileName = fmt.Sprintf("%s.zip", utils.GetBaseNameWithoutExt(fileTrees[0].FileName))
	}
	if err != nil {
		c.JSON(500, gin.H{"error": "服务器错误"})
		return
	}
	utils.SetDownloadHeader(fileName, c)
	c.Data(200, "application/octet-stream", buffer)
}
